(function (vc) {
    var DEFAULT_PAGE = 1;
    var DEFAULT_ROWS = 100;
    vc.extends({
        data: {
            orderInfo: {
                prods: [],
                total: 0,
                shopId: '',
                records: 1,
                moreCondition: false,
                totalMount: 0.00,
                totalNum: 0,
                conditions: {

                }
            },
            provs: [],
            citys: [],
            areas: [],
            addAddressInfo: {
                selectProv: '',
                selectCity: '',
                selectArea: '',
                addressId: '',
                userId: '',
                area: '',
                address: '',
                areaCode: '',
                province: '',
                city: '',
                postalCode: '',
                district: '',
                telNum: '',
                areaName:'',
                extensionNum: '',
                tel: '',
                zipCode: '',
                isDefault: '',
                createUser: '',
                createOrg: '',
                updateUser: '',
                updateOrg: '',
                provinceStr: '',
                cityStr: '',
                districtStr: '',
            },
            areaInfo: {
                conditions: {
                    pid: ''
                }
            },
            provinces:[],
            citys:[],
            districts:[],
            userAddresses:[],
            nowBuyProductId:''
        },
        _initMethod: function () {
            vc.component._listAddresses(DEFAULT_PAGE, DEFAULT_ROWS);
            vc.component._computeStoreOrderPrice(DEFAULT_PAGE, DEFAULT_ROWS);
            // if (vc.getParam("productId")) {
            //     vc.component.nowBuyProductId = vc.getParam("productId");
            //     vc.component._oneProdcut(DEFAULT_PAGE, DEFAULT_ROWS);
            // }else{
            //     vc.component._listOrderCarts(DEFAULT_PAGE, DEFAULT_ROWS);
            // }
        },
        _initEvent: function () {

        },
        methods: {
            getProv: function (_prov) {
                vc.component._selectArea('202', _prov);
            },
            getCity: function (_city) {
                vc.component._selectArea('303', _city);
            },
            getArea: function (_area) {
                vc.component.addAddressInfo.areaName = '';
                vc.component.addAddressInfo.areaCode = _area;
                if (!vc.component.provs) {
                    return;
                }
                vc.component.provs.forEach(function (_param) {
                    if (_param.areaCode == vc.component.addAddressInfo.selectProv) {
                        vc.component.addAddressInfo.areaName = _param.areaName;
                    }
                });
                vc.component.citys.forEach(function (_param) {
                    if (_param.areaCode == vc.component.addAddressInfo.selectCity) {
                        vc.component.addAddressInfo.areaName += _param.areaName;
                    }
                });
                vc.component.areas.forEach(function (_param) {
                    if (_param.areaCode == vc.component.addAddressInfo.selectArea) {
                        vc.component.addAddressInfo.areaName += _param.areaName;
                    }
                });
            },
            _selectArea: function (_areaLevel, _parentAreaCode) {
                let _param = {
                    params: {
                        areaLevel: _areaLevel,
                        parentAreaCode: _parentAreaCode
                    }
                };
                vc.http.apiGet('/area.listAreas',
                    _param,
                    function (json, res) {
                        if (res.status == 200) {
                            let _tmpAreas = JSON.parse(json).data;
                            if (_areaLevel == '101') {
                                vc.component.provs = _tmpAreas;
                            } else if (_areaLevel == '202') {
                                vc.component.citys = _tmpAreas;
                            } else {
                                vc.component.areas = _tmpAreas;
                            }
                            return;
                        }
                    },
                    function (errInfo, error) {
                        console.log('请求失败处理', errInfo, error);
                        vc.toast("查询地区失败");
                    });
            },
            _createOrder: function (shopId) {
                let _isDefault = 0;
                let _defaultAddrId = "";
                //选择地址
                vc.component.userAddresses.forEach(item => {
                    if(item.isDefault == "1"){
                        _isDefault += 1;
                        _defaultAddrId = item.addressId;
                    }
                });
                if(_isDefault != 1){
                    vc.message("请选择一个有效收货地址");
                    return;
                }
                //无商品提示
                if(vc.component.orderInfo.prods.length == 0){
                    vc.message("请选择商品");
                    return;
                }
                var param = {
                    products: vc.component.orderInfo.prods,
                    addressId: _defaultAddrId,
                    payType:"1001",
                    deliveryType:"1001",
                    shopId:shopId
                };
                //发送post请求
                vc.http.apiPost(
                    'storeOrder.saveStoreOrder',
                    JSON.stringify(param), {
                        emulateJSON: true
                    },
                    function(json, res) {
                        let _json = JSON.parse(json);
                        vc.toast("订单创建成功，正在跳转支付页面");
                        if (_json.code == 0) {
                            //关闭model
                            vc.jumpToPage("/pageLR.html#/pages/plateform/pay?orderId=" + _json.data.orderId);
                            return;
                        }
                    },
                    function(errInfo, error) {
                        console.log('请求失败处理');
                        vc.toast(errInfo);
                    });
            },
            calAddress : function(_select){
                if(_select.isDefault == "1"){
                    return "default-add";
                }else{
                    return "other-add";
                }
            },
            selectAddress:function(_select){
                vc.component.userAddresses.forEach(item => {
                    item.isDefault = "0";
                });
                _select.isDefault = "1";
            },
            deleteAddress:function(_addr){
                vc.http.apiPost(
                    'userAddress.deleteUserAddress',
                    JSON.stringify(_addr),
                    {
                        emulateJSON:true
                     },
                     function(json,res){
                        //vm.menus = vm.refreshMenuActive(JSON.parse(json),0);
                        let _json = JSON.parse(json);
                        if (_json.code == 0) {
                            vc.component._listAddresses(DEFAULT_PAGE, DEFAULT_ROWS);
                            return ;
                        }
                        vc.message(_json.msg);
                     },
                     function(errInfo,error){
                        console.log('请求失败处理');
                        vc.message(json);

                     });
            },
            //获取用户地址
            _listAddresses: function (_page, _rows) {
                var param = {
                    params: {page:_page,row:_rows,userId:vc.getData('/nav/getUserInfo').userId}
                };
                //发送get请求
                vc.http.apiGet('userAddress.queryUserAddress',
                    param,
                    function (json, res) {
                        var _addressInfo = JSON.parse(json);
                        vc.component.userAddresses = _addressInfo.data;
                    }, function (errInfo, error) {
                        console.log('请求失败处理');
                    }
                );
            },
            addAddressValidate() {
                return vc.validate.validate({
                    addAddressInfo: vc.component.addAddressInfo
                }, {
                    'addAddressInfo.username': [
                        {
                            limit: "required",
                            param: "",
                            errInfo: "收货人名称不能为空"
                        },
                        {
                            limit: "maxLength",
                            param: "30",
                            errInfo: "收货人名称不能超过30"
                        },
                    ],
                    'addAddressInfo.areaName': [
                        {
                            limit: "required",
                            param: "",
                            errInfo: "收货区域不能为空"
                        },
                        {
                            limit: "maxLength",
                            param: "50",
                            errInfo: "收货区域不能超过50"
                        },
                    ],
                    'addAddressInfo.address': [
                        {
                            limit: "required",
                            param: "",
                            errInfo: "详细地址不能为空"
                        },
                        {
                            limit: "maxLength",
                            param: "50",
                            errInfo: "详细地址不能超过50"
                        },
                    ],
                    'addAddressInfo.tel': [
                        {
                            limit: "required",
                            param: "",
                            errInfo: "手机号码不能为空"
                        },
                        {
                            limit: "phone",
                            param: "",
                            errInfo: "手机号格式错误"
                        },
                    ],
                });
            },
            saveAddressInfo: function () {
                // var provinceArr = vc.component.addAddressInfo.provinceStr.split('-');
                // var cityArr = vc.component.addAddressInfo.cityStr.split('-');
                // var districtArr = vc.component.addAddressInfo.districtStr.split('-');
                // vc.component.addAddressInfo.area = provinceArr[1] + '-' + cityArr[1] + '-' + districtArr[1];
                // vc.component.addAddressInfo.province = provinceArr[0];
                // vc.component.addAddressInfo.city = cityArr[0];
                // vc.component.addAddressInfo.district = districtArr[0];

                vc.component.addAddressInfo.userId = vc.getData('/nav/getUserInfo').userId;

                if (!vc.component.addAddressValidate()) {
                    vc.toast(vc.validate.errInfo);
                    return;
                }

                if (!vc.component.addAddressInfo.isDefault) {
                    vc.component.addAddressInfo.isDefault = '0';
                } else {
                    vc.component.addAddressInfo.isDefault = '1';
                }
                vc.http.apiPost(
                    'userAddress.saveUserAddress',
                    JSON.stringify(vc.component.addAddressInfo),
                    {
                        emulateJSON: true
                    },
                    function (json, res) {
                        //vm.menus = vm.refreshMenuActive(JSON.parse(json),0);
                        let _json = JSON.parse(json);
                        if (_json.code == 0) {
                            //关闭model
                            vc.component._listAddresses(DEFAULT_PAGE, DEFAULT_ROWS);
                            vc.component.clearAddAddressInfo();
                            $("#mask").hide();
                            $(".edit-address").hide();
                            return;
                        }
                        vc.toast(_json.msg);

                    },
                    function (errInfo, error) {
                        console.log('请求失败处理');

                        vc.toast(errInfo);

                    });
            },
            clearAddAddressInfo: function () {
                vc.component.addAddressInfo = {
                    addressId: '',
                    userId: '',
                    consignee: '',
                    area: '',
                    streetAddress: '',
                    phone: '',
                    areaCode: '',
                    province: '',
                    city: '',
                    district: '',
                    telNum: '',
                    extensionNum: '',
                    tel: '',
                    zipCode: '',
                    isDefault: '',
                    createUser: '',
                    createOrg: '',
                    updateUser: '',
                    updateOrg: '',
                    provinceStr: '',
                    cityStr: '',
                    districtStr: '',
                };
            },
            selectAdd: function (type) {
                var pid;
                if (type == 'city') {
                    pid = vc.component.addAddressInfo.provinceStr.split('-')[0];
                    vc.component._listArea(pid,type);
                    vc.component.addAddressInfo.cityStr = '';
                    vc.component.addAddressInfo.districtStr = '';
                }
                if (type == 'district') {
                    pid = vc.component.addAddressInfo.cityStr.split('-')[0];
                    vc.component._listArea(pid,type);
                    vc.component.addAddressInfo.districtStr = '';
                }
            },
            _listArea: function (_pid, _type) {
                vc.component.areaInfo.conditions.page = -1;
                vc.component.areaInfo.conditions.row = 0;
                vc.component.areaInfo.conditions.pid = _pid;
                var param = {
                    params: vc.component.areaInfo.conditions
                }
                vc.http.apiGet(
                    'area.listArea',
                    param,
                    function (json, res) {
                        var _json = JSON.parse(json);
                        if (_type == 'province') {
                            vc.component.provinces = _json.data;
                        }
                        if (_type == 'city') {
                            vc.component.citys = _json.data;
                        }
                        if (_type == 'district') {
                            vc.component.districts = _json.data;
                        }
                    }, function (errInfo, error) {
                        console.log('请求失败处理');
                    }
                );
            },
            _caculTotalMount: function () {
                let j = 0,k =0;
                vc.component.orderInfo.prods.forEach(item => {
                    if (!isNaN(item.cartNum) && !isNaN(item.price)) {
                        j += parseFloat(item.cartNum) * parseFloat(item.price).toFixed(2);
                        k += parseFloat(item.cartNum)
                    } else {
                        $that.orderInfo.totalMount = "请输入正确的数字";
                        $that.orderInfo.totalNum = "请输入正确的数字";
                        throw Error();
                    }
                });
                $that.orderInfo.totalMount = j.toFixed(2);
                $that.orderInfo.totalNum = k;
            },
            //获取购物车订单
            _listOrderCarts: function (_page, _rows) {
                vc.component.orderInfo.conditions.page = _page;
                vc.component.orderInfo.conditions.row = _rows;
                var param = {
                    params: vc.component.orderInfo.conditions
                };
                //发送get请求
                vc.http.apiGet('storeCart.listStoreCart',
                    param,
                    function (json, res) {
                        var _orderInfo = JSON.parse(json);
                        vc.component.orderInfo.total = _orderInfo.total;
                        vc.component.orderInfo.records = _orderInfo.records;
                        vc.component.orderInfo.prods = _orderInfo.data;
                        vc.component._caculTotalMount();
                    }, function (errInfo, error) {
                        console.log('请求失败处理');
                    }
                );
            },
            //获取单个物品信息
            _oneProdcut: function (_page, _rows) {
                var param = {
                    params: {
                        productId:vc.getParam("productId"),
                        page:_page,
                        row:_rows
                    }
                };
                //发送get请求
                vc.http.apiGet('storeCart.listStoreCart',
                    param,
                    function (json, res) {
                        var _orderInfo = JSON.parse(json);
                        vc.component.orderInfo.total = _orderInfo.total;
                        vc.component.orderInfo.records = _orderInfo.records;
                        vc.component.orderInfo.prods = _orderInfo.data;
                        //vc.component._caculTotalMount();
                    }, function (errInfo, error) {
                        console.log('请求失败处理');
                    }
                );
            },
            //新增地址
            addAddr: function () {
                $("#mask").css("height", $(document).height()).show();
                $(".edit-address").show();
                $("#id").val('');
                $("#sh-name").val('');
                $("#sh-phone").val($("#user_mobile").val());
                $("#sh-tel").val('');
                $("#district").val('');
                $("#sh-address").val('');
                $("#sh-postcode").val('');
                $("#isdefault").removeAttr("checked");
                vc.component._selectArea('101', '0');
            },
             closeTips:function(){
                $("#mask").hide();
                $(".edit-address").hide();
            },
            //获取购物车订单
            _computeStoreOrderPrice: function (_page, _rows) {
                var param = {
                    params: {
                        page:_page,
                        row:_rows,
                        shopId: vc.getParam("shopId"),
                        cartType:'3306',
                        productId: vc.getParam("productId"),
                        valueId: vc.getParam("valueId"),
                        goodsNum: vc.getParam("goodsNum"),
                        killId: vc.getParam("killId")
                    }
                };
                //发送get请求
                vc.http.apiGet('storeOrder.computeStoreOrderPrice',
                    param,
                    function (json, res) {
                        var _orderInfo = JSON.parse(json);
                        vc.component.orderInfo.total = _orderInfo.total;
                        vc.component.orderInfo.records = _orderInfo.records;
                        vc.component.orderInfo.prods = _orderInfo.data.goods;
                        vc.component.orderInfo.shopId = vc.getParam("shopId"),
                        vc.component._caculTotalMountNew();
                    }, function (errInfo, error) {
                        console.log('请求失败处理');
                    }
                );
            },
            _caculTotalMountNew: function () {
                let j = 0,k =0;
                vc.component.orderInfo.prods.forEach(item => {
                    if (!isNaN(item.goodsNum) && !isNaN(item.ownerPrice)) {
                        j += parseFloat(item.goodsNum) * parseFloat(item.ownerPrice).toFixed(2);
                        k += parseFloat(item.goodsNum)
                    } else {
                        $that.orderInfo.totalMount = "请输入正确的数字";
                        $that.orderInfo.totalNum = "请输入正确的数字";
                        throw Error();
                    }
                });
                $that.orderInfo.totalMount = j.toFixed(2);
                $that.orderInfo.totalNum = k;
            },
        }
    });

})(window.vc);
